package com.gzkemays.music.controller;

import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("/minio")
@Slf4j
public class MinioController {
  @Value("${minio.endpoint}")
  private String ENDPOINT;

  @Value("${minio.bucketName}")
  private String BUCKETNAME;

  @Value("${minio.accessKey}")
  private String ACCESSKEY;

  @Value("${minio.secretKey}")
  private String SECRETKEY;
  /**
   * 下载文件
   *
   * @throws IOException
   */
  @GetMapping("/downloadFiles")
  public void downloadFiles(
      @RequestParam("filename") String filename, HttpServletResponse httpResponse) {
    try {
      MinioClient minioClient = new MinioClient(ENDPOINT, ACCESSKEY, SECRETKEY);
      InputStream object = minioClient.getObject(BUCKETNAME, filename);
      byte buf[] = new byte[1024];
      int length = 0;
      httpResponse.reset();
      httpResponse.setHeader(
          "Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
      httpResponse.setContentType("application/octet-stream");
      httpResponse.setCharacterEncoding("utf-8");
      OutputStream outputStream = httpResponse.getOutputStream();
      while ((length = object.read(buf)) > 0) {
        outputStream.write(buf, 0, length);
      }
      outputStream.close();
    } catch (Exception ex) {
      log.info("导出失败：", ex.getMessage());
    }
  }
}
